package com.villaday.idf.activity;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.adapter.VipRuleRVAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.custom.ShareDialog;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.VipRuleEntity;
import com.villaday.idf.model.VipsInviteShareEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.OkHttpUtil.OnDataListener;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 邀请好友成为VIP
 */
public class InviteFriendActivity extends BaseActivity implements OnDataListener {


    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.rv_vip_rule)
    public RecyclerView recyclerView;

    public SimpleDraweeView simpleDraweeView;
    private Gson gson = new GsonBuilder().create();
    private LoadingDialog loadingDialog;

    private VipRuleRVAdapter vipRuleRVAdapter;
    private RefreshtokenEntity refreshtoken;

    VipsInviteShareEntity.BodyBean shareBody;

    @Override
    protected int getViewResId() {
        return R.layout.activity_invited_friend;
    }

    @Override
    protected void init() {
        ToolBarUtil.initToolBar(toolbar, "邀请好友", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        vipRuleRVAdapter = new VipRuleRVAdapter(this);
        recyclerView.setAdapter(vipRuleRVAdapter);

        recyclerView.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 8)));

        View inflate = View.inflate(this, R.layout.item_head_vip_rule, null);
        simpleDraweeView = (SimpleDraweeView) inflate.findViewById(R.id.sdv_vip);
        vipRuleRVAdapter.addHeaderView(inflate);
//        vipRuleRVAdapter.setEmptyView(R.layout.empty_tips);
//        vipRuleRVAdapter.setEmptyTips(R.id.tv_emptyTips, "暂无相关数据");
        loadingDialog = LoadingDialog.newInstance("加载中...");
        loadingDialog.show(getFragmentManager());
    }

    @Override
    protected void loadData() {
        OkHttpUtil.getJSON(this, Constant.URL.vips_invite_rule, this);
        OkHttpUtil.getJSON(this, Constant.URL.vips_invite_share, this);//分享内容
        getData();
    }


    private void getData() {
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map, this);
    }

    @OnClick({R.id.tv_invite_btn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_invite_btn: {
                if (shareBody != null) {
                    if ("mini".equals(shareBody.getType())) {
                        shareXCX();
                    } else {
                        ShareDialog shareDialog = ShareDialog.newInstance();
                        shareDialog.show(getFragmentManager());
                        shareDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(View v) {
                                switch (v.getId()) {
                                    case R.id.tv_Swx: {
                                        if ("mini".equals(shareBody.getType())) {
                                            shareXCX();
                                        } else if ("music".equals(shareBody.getType())) {
                                            shareXMusic(0);
                                        } else if ("video".equals(shareBody.getType())) {
                                            shareXVideo(0);
                                        } else if ("link".equals(shareBody.getType())) {
                                            share(0);
                                        } else if ("text".equals(shareBody.getType())) {
                                            shareXText(0);
                                        } else if ("image".equals(shareBody.getType())) {
                                            shareXPhoto(0);
                                        }
                                    }
                                    break;
                                    case R.id.tv_Spyq: {
                                        if ("mini".equals(shareBody.getType())) {
                                            share(1);
                                        } else if ("music".equals(shareBody.getType())) {
                                            shareXMusic(1);

                                        } else if ("video".equals(shareBody.getType())) {
                                            shareXVideo(1);

                                        } else if ("link".equals(shareBody.getType())) {
                                            share(1);


                                        } else if ("text".equals(shareBody.getType())) {
                                            shareXText(1);

                                        } else if ("image".equals(shareBody.getType())) {
                                            shareXPhoto(1);

                                        }

                                    }
                                    break;
                                    case R.id.tv_Ssave: {
                                        if ("mini".equals(shareBody.getType())) {
                                            share(2);

                                        } else if ("music".equals(shareBody.getType())) {
                                            shareXMusic(2);

                                        } else if ("video".equals(shareBody.getType())) {
                                            shareXVideo(2);

                                        } else if ("link".equals(shareBody.getType())) {
                                            share(2);


                                        } else if ("text".equals(shareBody.getType())) {
                                            shareXText(2);


                                        } else if ("image".equals(shareBody.getType())) {
                                            shareXPhoto(2);

                                        }
                                    }
                                    break;
                                }
                            }
                        });
                    }
                }
            }
            break;
        }
    }


    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {

            dismissLoading();
            if (Constant.URL.vips_invite_rule.equals(url)) {
                LogeUtil.e("rule", json);
                VipRuleEntity vre = gson.fromJson(json, VipRuleEntity.class);
                if ("200".equals(vre.getCode())) {
                    simpleDraweeView.setImageURI(Uri.parse(vre.getBody().getImageUrl()));
                    vipRuleRVAdapter.setData(vre.getBody().getRules());
                }
            } else if (Constant.URL.vips_invite_share.equals(url)) {
                LogeUtil.e("vips_invite_share", json);
                VipsInviteShareEntity vre = gson.fromJson(json, VipsInviteShareEntity.class);
                if ("200".equals(vre.getCode())) {
                    shareBody = vre.getBody();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            saveImageToSdCard(InviteFriendActivity.this, shareBody.getImageUrl());
                        }
                    }).start();
                }
            } else if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                LogeUtil.e("refresh_token", json);
                dismissLoading();
                refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                    //改变 主页bottom vip 图标及文字颜色
                    mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor),refreshtoken.getBody().getMember().getType());

                } else {
                    ToastUtil.initToast(this, refreshtoken.getMsg());
                }
            }
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }


    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    public static String IMAGE_NAME = "shareVip";

    //根据网络图片url路径保存到本地
    public File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME +System.currentTimeMillis()+ ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }


    private void shareXText(int i) {//0 聊天1 朋友圈 其他收藏

        WXTextObject miniProgramObj = new WXTextObject(shareBody.getTitle());
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.description = shareBody.getTitle();
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "text";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXPhoto(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;

        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        WXImageObject miniProgramObj = new WXImageObject(bitmap);
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        //Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXVideo(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXVideoObject miniProgramObj = new WXVideoObject();
        miniProgramObj.videoUrl = shareBody.getLink(); // 音乐
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "video";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXMusic(int i) {//0 聊天1 朋友圈 其他收藏

        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXMusicObject miniProgramObj = new WXMusicObject();
        miniProgramObj.musicUrl = shareBody.getLink(); // 音乐
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 30 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "music";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void shareXCX() {
        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;


        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = TextUtils.isEmpty(shareBody.getLink()) ? "https://idfh5.villaday.com/download.html" : shareBody.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
        miniProgramObj.userName = shareBody.getMiniAppId();     // 小程序原始id
        miniProgramObj.path = shareBody.getPath();            //小程序页面路径
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title = shareBody.getTitle();                 // 小程序消息title
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);

        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);

        api.sendReq(req);
    }

    private void share(int i) {
        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = this.getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;
        String sharefileName = externalCacheDir.getPath() + "/12306" + imageFileName;


        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareBody.getLink();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = shareBody.getTitle();
        msg.description = shareBody.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);
        /*Bitmap bitmap1 = BitMapUtil.compressBitmap(bitmap, 31*1024);
        BitMapUtil.saveBitmap2File(bitmap1,sharefileName);
        Bitmap bitmap2 = BitMapUtil.getBitmap(sharefileName);*/
        //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.share);
        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 31 * 1024);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);
        api.sendReq(req);

    }

}
